package edu.hda.pt.client.connections.netty;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipelineCoverage;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;

import edu.hda.pt.client.connections.PTClientNetty;

/**
 * Event handler for receiving synchronous messages
 * 
 * @author Marc Hammerton
 * 
 */
@ChannelPipelineCoverage("one")
public class SyncClientHandler extends ClientHandler {

	private PTClientNetty client;

	/**
	 * Queue for taking values of synchronous messages
	 */
	final BlockingQueue<String> answer = new LinkedBlockingQueue<String>();

	/**
	 * Constructor setting the client object
	 * 
	 * @param client
	 *            - client object
	 */
	public SyncClientHandler(PTClientNetty client) {
		this.client = client;
	}

	/**
	 * This method is called when a message from the server is received. The
	 * message value is put into the queue.
	 * 
	 * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(ChannelHandlerContext,
	 *      MessageEvent)
	 */
	@Override
	public void messageReceived(ChannelHandlerContext chx, final MessageEvent e) {
		answer.offer(e.getMessage().toString());
	}

	/**
	 * This method is called whenever an exception is caught. It prints the
	 * exception.
	 * 
	 * @see org.jboss.netty.channel.SimpleChannelHandler#exceptionCaught(ChannelHandlerContext,
	 *      ExceptionEvent)
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		System.out.println(client.clientID + " Exception:");
		System.out.println(e.getCause());
	}

	/**
	 * This method is called when a message is written.
	 * 
	 * @see org.jboss.netty.channel.SimpleChannelHandler#writeRequested(ChannelHandlerContext,
	 *      MessageEvent)
	 */
	@Override
	public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		super.writeRequested(ctx, e);
	}

	/**
	 * @see edu.hda.pt.client.connections.netty.ClientHandler#responseReceived()
	 */
	public String responseReceived() {
		for (;;) {
			try {
				return answer.take();
			} catch (InterruptedException e) {
				// Ignore.
			}
		}
	}

}
